<template>
  <div class="user-bookings">
    <h2 class="page-title">我的预订</h2>
    
    <!-- 预订列表 -->
    <div v-if="bookingList.length > 0">
      <el-card v-for="booking in bookingList" :key="booking.id" class="booking-card">
        <div class="booking-header">
          <h3 class="booking-title">
            <router-link :to="`/homestay/${booking.homestayId}`">{{ booking.name }}</router-link>
          </h3>
          <el-tag :type="getStatusType(booking.status)" size="small">{{ booking.status }}</el-tag>
        </div>
        
        <div class="booking-info">
          <div class="booking-date">
            <i class="el-icon-date"></i>
            <span>{{ booking.startDate.substring(0, 10) }} 至 {{ booking.endDate.substring(0, 10) }}</span>
            <span class="booking-days">共{{ booking.days }}晚</span>
          </div>
          
          <div class="booking-price">
            总价: <span class="price-value">¥{{ booking.totalPrice }}</span>
          </div>
        </div>
        
        <div class="booking-actions">
          <el-button 
            size="small" 
            type="primary" 
            @click="viewBookingDetail(booking)"
          >
            查看详情
          </el-button>
          
          <el-button 
            size="small" 
            :type="booking.status === '已确认' ? 'danger' : 'info'"
            :disabled="booking.status !== '已确认'"
            @click="handleCancelBooking(booking)"
          >
            {{ booking.status === '已确认' ? '取消预订' : '无法取消' }}
          </el-button>
          
          <el-button
            v-if="booking.status === '待支付'"
            size="small"
            type="success"
            @click="handlePayment(booking)"
          >
            去支付
          </el-button>
          
          <el-button
            v-if="booking.status === '已确认'"
            size="small"
            type="warning"
            @click="handleViewCardKey(booking)"
          >
            房卡密码
          </el-button>
          
          <el-button
            v-if="booking.status === '待支付' || booking.status === '已取消预订' || booking.status === '已同意退款'"
            size="small"
            type="info"
            @click="handleRemoveBooking(booking)"
          >
            移除预订
          </el-button>
        </div>
        
        <div class="booking-time">
          预订时间: {{ booking.time }}
        </div>
      </el-card>
      
      <!-- 分页 -->
      <div class="pagination-section" v-if="bookingList.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :total="totalBookings"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>
    
    <!-- 空状态 -->
    <el-empty 
      v-else 
      description="暂无预订记录" 
      :image-size="200"
    >
      <el-button type="primary" @click="goToHomestayList">浏览民宿</el-button>
    </el-empty>
    
    <!-- 取消预订确认对话框 -->
    <el-dialog
      title="取消预订"
      v-model="cancelDialogVisible"
      width="400px"
    >
      <p>确定要取消预订 <strong>{{ currentBooking?.name }}</strong> 吗？</p>
      <p class="cancel-warning">取消预订后，请联系 <strong>17825985258</strong> 办理退款。</p>
      
      <template #footer>
        <el-button @click="cancelDialogVisible = false">返回</el-button>
        <el-button type="danger" @click="confirmCancelBooking" :loading="cancelLoading">
          确认取消
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 移除预订确认对话框 -->
    <el-dialog
      title="移除预订"
      v-model="removeDialogVisible"
      width="400px"
    >
      <p>确定要从列表中移除此预订记录吗？</p>
      <p class="warning">此操作将从系统中永久删除该预订记录，且无法恢复！</p>
      
      <template #footer>
        <el-button @click="removeDialogVisible = false">返回</el-button>
        <el-button type="danger" @click="confirmRemoveBooking" :loading="removeLoading">
          确认移除
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 预订详情对话框 -->
    <el-dialog
      title="预订详情"
      v-model="detailDialogVisible"
      width="600px"
    >
      <div v-if="currentBooking" class="booking-detail">
        <h3 class="detail-title">{{ currentBooking.name }}</h3>
        
        <el-descriptions :column="1" border>
          <el-descriptions-item label="预订状态">
            <el-tag :type="getStatusType(currentBooking.status)">{{ currentBooking.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预订编号">{{ currentBooking.id }}</el-descriptions-item>
          <el-descriptions-item label="入住日期">{{ currentBooking.startDate.substring(0, 10) }}</el-descriptions-item>
          <el-descriptions-item label="退房日期">{{ currentBooking.endDate.substring(0, 10) }}</el-descriptions-item>
          <el-descriptions-item label="入住天数">{{ currentBooking.days }}晚</el-descriptions-item>
          <el-descriptions-item label="房间类型">{{ currentBooking.roomType || '标准房' }}</el-descriptions-item>
          <el-descriptions-item label="预订人数">{{ currentBooking.guestCount || 2 }}人</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ currentBooking.contactName || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentBooking.contactPhone || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="特殊要求">{{ currentBooking.requirements || '无' }}</el-descriptions-item>
          <el-descriptions-item label="总价">
            <span class="price-value">¥{{ currentBooking.totalPrice }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="预订时间">{{ currentBooking.time }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-actions">
          <el-button
            v-if="currentBooking.status === '待支付'"
            type="success"
            @click="handlePayment(currentBooking)"
          >
            去支付
          </el-button>
          
          <el-button 
            v-if="currentBooking.status === '已确认'"
            type="danger"
            @click="handleCancelFromDetail(currentBooking)"
          >
            取消预订
          </el-button>
          
          <el-button 
            v-if="currentBooking.status === '已确认'"
            type="warning"
            @click="handleViewCardKey(currentBooking)"
          >
            查看房卡密码
          </el-button>
          
          <el-button 
            v-if="currentBooking.status === '待支付' || currentBooking.status === '已取消预订' || currentBooking.status === '已同意退款'"
            type="info"
            @click="handleRemoveFromDetail(currentBooking)"
          >
            移除预订
          </el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 支付对话框 -->
    <el-dialog
      title="支付确认"
      v-model="paymentDialogVisible"
      width="450px"
    >
      <div v-if="currentBooking" class="payment-dialog">
        <h3>支付金额: <span class="price-value">¥{{ currentBooking.totalPrice }}</span></h3>
        
        <div class="payment-methods">
          <p class="payment-title">选择支付方式:</p>
          <el-radio-group v-model="paymentMethod">
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="alipay">支付宝</el-radio>
          </el-radio-group>
        </div>
        
        <div class="payment-qrcode" v-if="paymentMethod">
          <p>请扫描下方二维码完成支付</p>
          <div class="qrcode-container">
            <img style="width: 200px; height: 200px;" src="@/assets/44.jpg" alt="支付二维码">

          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="paymentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPayment" :loading="paymentLoading">
          确认已扫码支付
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 房卡密码对话框 -->
    <el-dialog
      title="房卡密码"
      v-model="cardKeyDialogVisible"
      width="450px"
      class="card-key-dialog"
    >
      <div v-if="cardKeyLoading" class="card-key-loading">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <p>正在获取房卡信息...</p>
      </div>
      
      <div v-else class="card-key-info">
        <template v-if="cardKeyInfo && cardKeyInfo !== null">
          <div class="key-code-section">
            <h3>房卡密码:</h3>
            <div class="key-code">{{ cardKeyInfo }}</div>
            <p class="key-instruction">请前往房卡柜输入以上密码领取房卡</p>
          </div>
        </template>
        <template v-else>
          <div class="key-empty-section">
            <h3>暂无密码</h3>
            <p class="contact-info">请打电话 <a :href="'tel:17825985258'">17825985258</a> 联系办理入住</p>
          </div>
        </template>
      </div>
      
      <template #footer>
        <el-button @click="cardKeyDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
// 移除不需要的导入
// import { ElMessage, ElMessageBox } from 'element-plus'
import { ElMessage } from 'element-plus'
import { bookings as mockBookings } from '../mock'
// import { bookingApi } from '../api'
import request from '@/utils/request'
// 路由
const router = useRouter()

// 当前页码
const currentPage = ref(1)
const pageSize = ref(5)
const totalBookings = ref(0)

// 预订列表
const bookingList = ref([])

// 取消预订相关
const cancelDialogVisible = ref(false)
const currentBooking = ref(null)
const cancelLoading = ref(false)

// 移除预订相关
const removeDialogVisible = ref(false)
const removeLoading = ref(false)

// 详情对话框
const detailDialogVisible = ref(false)

// 支付相关
const paymentDialogVisible = ref(false)
const paymentMethod = ref('wechat')
const paymentLoading = ref(false)
const iconError = ref(false)

// 房卡密码相关
const cardKeyDialogVisible = ref(false)
const cardKeyInfo = ref(null)
const cardKeyLoading = ref(false)

// 获取预订列表
const fetchBookingList = async () => {
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      userId: JSON.parse(localStorage.getItem('user')).id
    }

    console.log('获取预订列表，参数:', params);

    // 发送请求获取预约列表
    const res = await request.get('/bookings/page', { params })
    
    console.log('获取预订列表响应:', res.data);
    
    // 处理返回结果
    if(res.data && res.data.data) {
      bookingList.value = res.data.data.records || [];
      totalBookings.value = res.data.data.total || bookingList.value.length;
      console.log('预约数据已更新:', bookingList.value);
    } else {
      console.error('响应数据格式不正确:', res.data);
      ElMessage.warning('获取预订数据格式不正确');
      
      // 如果返回格式不正确，尝试使用本地假数据
      const data = mockBookings;
      bookingList.value = data;
      totalBookings.value = data.length;
    }
  } catch (error) {
    console.error('获取预约列表失败:', error);
    ElMessage.error('获取预约列表失败，使用本地数据');
    
    // 使用模拟数据
    const data = mockBookings;
    bookingList.value = data;
    totalBookings.value = data.length;
  } 
}

// 根据状态获取标签类型
const getStatusType = (status) => {
  switch (status) {
    case '已确认':
      return 'success'
    case '已完成':
      return 'info'
    case '已取消预订':
      return 'danger'
    case '待支付':
      return 'warning'
    case '已同意退款':
      return 'success'
    default:
      return 'info'
  }
}

// 查看预订详情
const viewBookingDetail = (booking) => {
  currentBooking.value = booking
  detailDialogVisible.value = true
}

// 处理取消预订
const handleCancelBooking = (booking) => {
  if (booking.status !== '已确认') {
    ElMessage.warning('只能取消已确认状态的预订')
    return
  }
  
  currentBooking.value = booking
  cancelDialogVisible.value = true
}

// 从详情页面取消
const handleCancelFromDetail = (booking) => {
  detailDialogVisible.value = false
  setTimeout(() => {
    handleCancelBooking(booking)
  }, 300)
}

// 确认取消预订
const confirmCancelBooking = async () => {
  if (!currentBooking.value) return
  
  cancelLoading.value = true
  
  try {
    // 首先尝试使用PUT方法，这通常用于更新资源状态
    console.log('使用PUT方法发送取消预订请求:', currentBooking.value.id);
    
    // 尝试不同的API路径和参数结构
    const res = await request.post(`/bookings/deleteView/${currentBooking.value.id}`, {
      id: currentBooking.value.id,
      status: '已取消'
    });
    
    console.log('取消预订响应:', res.data);
    
    if (res.data.code === '200') {
      // 模拟请求延迟
      await new Promise(resolve => setTimeout(resolve, 1000))
    
      // 直接强制指定状态
      bookingList.value = bookingList.value.map(item => {
        if (item.id === currentBooking.value.id) {
          console.log(`将预订 ${item.id} 的状态从 ${item.status} 更改为 已取消`);
          return { ...item, status: '已取消' };
        }
        return item;
      });
      
      // 如果详情对话框打开，同步更新 currentBooking
      if (detailDialogVisible.value && currentBooking.value) {
        console.log('更新详情页面中的状态为已取消');
        currentBooking.value.status = '已取消';
      }
    
      ElMessage.success('预订已成功取消')
      
      // 立即刷新
      fetchBookingList();
      
      cancelDialogVisible.value = false
    }
  } catch (error) {
    console.error('取消预订失败:', error)
  
  } finally {
    cancelLoading.value = false
  }
}

// 处理移除预订
const handleRemoveBooking = (booking) => {
  currentBooking.value = booking
  removeDialogVisible.value = true
}

// 确认移除预订
const confirmRemoveBooking = async () => {
  if (!currentBooking.value) return
  
  removeLoading.value = true
  
  try {
    // 调用删除接口
    const res = await request.delete(`/bookings/${currentBooking.value.id}`)
    
    if (res.data.code === '200') {
      // 模拟请求延迟
      await new Promise(resolve => setTimeout(resolve, 1000))
    
      ElMessage.success('预订已成功移除')
      fetchBookingList();
      removeDialogVisible.value = false
    }
  } catch (error) {
    console.error('移除预订失败:', error)
    ElMessage.error('移除预订失败，请稍后重试')
  } finally {
    removeLoading.value = false
  }
}

// 处理支付
const handlePayment = (booking) => {
  currentBooking.value = booking
  paymentMethod.value = 'wechat' // 默认选中微信支付
  iconError.value = false // 重置图标错误状态
  paymentDialogVisible.value = true
}

// 确认支付
const confirmPayment = async () => {
  if (!currentBooking.value) return
  
  paymentLoading.value = true
  
  try {
    console.log('发送支付请求:', currentBooking.value.id, paymentMethod.value);
    const res = await request.post(`/bookings/view/${currentBooking.value.id}`, {
      paymentMethod: paymentMethod.value
    })
    
    console.log('支付响应:', res.data);
    
    if (res.data.code === '200') {
      // 模拟请求延迟
      await new Promise(resolve => setTimeout(resolve, 1500))
      
      // 更新本地数据状态
      const index = bookingList.value.findIndex(item => item.id === currentBooking.value.id)
      if (index !== -1) {
        bookingList.value[index].status = '已确认'
        console.log('更新了本地支付状态为已确认');
      }
      
      // 如果详情对话框打开，同步更新 currentBooking
      if (detailDialogVisible.value) {
        currentBooking.value.status = '已确认'
      }
      
      ElMessage.success(`通过${getPaymentMethodText(paymentMethod.value)}支付成功`)
      paymentDialogVisible.value = false
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请稍后重试')
  } finally {
    paymentLoading.value = false
  }
}

// 获取支付方式显示文本
const getPaymentMethodText = (method) => {
  const methodMap = {
    wechat: '微信支付',
    alipay: '支付宝',
    unionpay: '银联支付',
    creditcard: '信用卡支付',
    applepay: 'Apple Pay'
  }
  return methodMap[method] || method
}

// 查看房卡密码
const handleViewCardKey = async (booking) => {
  if (booking.status !== '已确认') {
    ElMessage.warning('只有已确认的预订才能查看房卡密码')
    return
  }
  
  currentBooking.value = booking
  cardKeyDialogVisible.value = true
  cardKeyLoading.value = true
  cardKeyInfo.value = null
  
  try {
    const res = await request.get(`/bookings/viewPassword/${booking.id}`)
    
    if (res.data.code === '200') {
      // 直接使用返回的数据，包括null值
      cardKeyInfo.value = res.data.data;
      console.log('获取房卡密码:', cardKeyInfo.value);
      
      // 如果返回null，提示用户
      if (cardKeyInfo.value === null) {
        console.log('房卡密码为空，需要联系电话办理');
      }
    } else {
      ElMessage.error(res.data.message || '获取房卡密码失败')
      cardKeyInfo.value = null
    }
  } catch (error) {
    console.error('获取房卡密码失败:', error)
    ElMessage.error('获取房卡密码失败，请稍后重试')
    cardKeyInfo.value = null
  } finally {
    cardKeyLoading.value = false
  }
}

// 页码变化处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchBookingList()
  window.scrollTo(0, 0)
}

// 每页大小变化处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchBookingList()
}

// 跳转到民宿列表
const goToHomestayList = () => {
  router.push('/')
}

// 从详情页面移除
const handleRemoveFromDetail = (booking) => {
  detailDialogVisible.value = false
  setTimeout(() => {
    handleRemoveBooking(booking)
  }, 300)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchBookingList()
})
</script>

<style scoped>
.user-bookings {
  padding-bottom: 2rem;
}

.page-title {
  margin-top: 0;
  margin-bottom: 1.5rem;
  font-size: 1.5rem;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.8rem;
}

.booking-card {
  margin-bottom: 1.5rem;
}

.booking-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.booking-title {
  margin: 0;
  font-size: 1.2rem;
}

.booking-title a {
  color: #333;
  text-decoration: none;
}

.booking-title a:hover {
  color: #409eff;
}

.booking-info {
  margin-bottom: 1rem;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 1rem;
  color: #666;
}

.booking-date {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.booking-days {
  background-color: #f0f9eb;
  color: #67c23a;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 0.8rem;
  margin-left: 0.5rem;
}

.booking-price {
  font-weight: 500;
}

.price-value {
  color: #f56c6c;
  font-weight: bold;
  font-size: 1.1rem;
}

.booking-actions {
  display: flex;
  gap: 0.8rem;
  margin-bottom: 1rem;
}

.booking-time {
  font-size: 0.8rem;
  color: #999;
  text-align: right;
}

.pagination-container {
  text-align: center;
  margin-top: 2rem;
}

.cancel-warning {
  color: #e6a23c;
  font-size: 0.9rem;
}

/* 预订详情样式 */
.booking-detail {
  padding: 0.5rem;
}

.detail-title {
  margin-top: 0;
  margin-bottom: 1.2rem;
  font-size: 1.3rem;
  color: #333;
  text-align: center;
  border-bottom: 1px dashed #eee;
  padding-bottom: 1rem;
}

.detail-actions {
  margin-top: 1.5rem;
  display: flex;
  justify-content: center;
  gap: 1rem;
}

/* 支付对话框样式 */
.payment-dialog {
  text-align: center;
}

.payment-methods {
  margin: 1.5rem 0;
  text-align: center;
}

.payment-methods .el-radio-group {
  display: flex;
  flex-direction: row;
  justify-content: center;
  gap: 30px;
}

.payment-title {
  margin-bottom: 1.2rem;
  font-weight: 500;
  text-align: center;
  font-size: 16px;
}

.qrcode-placeholder {
  margin: 1.5rem 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.qrcode-container {
  position: relative;
  display: inline-block;
  margin: 20px auto;
  border: 1px solid #eaeaea;
  border-radius: 8px;
  padding: 10px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.payment-icon-overlay {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.payment-logo {
  width: 40px;
  height: 40px;
  object-fit: contain;
}

.payment-text {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.card-payment-form,
.apple-pay-container,
.apple-pay-button,
.apple-pay-note {
  display: none;
}

/* 房卡密码对话框样式 */
.card-key-loading {
  text-align: center;
  padding: 30px 0;
}

.loading-icon {
  font-size: 30px;
  margin-bottom: 10px;
  color: #409eff;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.card-key-info {
  padding: 20px;
  text-align: center;
}

.key-code-section, .key-empty-section {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.key-code {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin: 15px 0;
  letter-spacing: 2px;
  font-family: monospace;
  background-color: #ecf5ff;
  border: 1px dashed #b3d8ff;
  border-radius: 4px;
  padding: 10px;
  display: inline-block;
}

.key-instruction {
  color: #67c23a;
  font-size: 16px;
  margin-top: 10px;
}

.contact-info {
  font-size: 16px;
  margin-top: 15px;
  color: #606266;
}

.contact-info a {
  color: #409eff;
  text-decoration: none;
  font-weight: bold;
}

@media (max-width: 768px) {
  .booking-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.8rem;
  }
  
  .booking-info {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .payment-methods .el-radio-group {
    flex-direction: column;
    align-items: center;
    gap: 15px;
  }
  
  .key-code {
    font-size: 24px;
    padding: 8px;
  }
}
</style> 